package com.huluobo.jetpackkotlindemo.paging

import android.content.Context
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.asLiveData
import androidx.lifecycle.viewModelScope
import androidx.paging.*
import com.huluobo.jetpackkotlindemo.paging.db.AppDatabase
import com.huluobo.jetpackkotlindemo.paging.db.RepoEntity
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map

/**
 * Created by lc on 2022/12/19.
 */
class PagingViewModel : ViewModel() {
    fun getPagingData(): Flow<PagingData<Repo>> {
        return Repository.getPagingData().cachedIn(viewModelScope)
    }

    fun getPagingData2(context: Context): LiveData<PagingData<Repo>> =
        Repository.getPagingData2(context).cachedIn(viewModelScope).asLiveData()
}


//Repo中实现网络请求
object Repository {
    const val PAGE_SIZE = 5
    private val gitHubService = ApiService.create()
    private val db = AppDatabase.instance
    fun getPagingData(): Flow<PagingData<Repo>> {
        //prefetchDistance 表示距离底部多少条数据开始预加载
        //设置0则表示滑动到底部才加载,默认值为分页的大小
        //如果想让用户对加载无感,则适当增加这个值即可,比如现在咱们调整分页大小的5倍
        return Pager(config = PagingConfig(pageSize = PAGE_SIZE, prefetchDistance = PAGE_SIZE * 5),
            pagingSourceFactory = { RepoPagingSource(gitHubService) }).flow
    }

    private val pagingConfig = PagingConfig(
        // 每页显示的数据的大小
        pageSize = PAGE_SIZE,
        // 开启占位符
        enablePlaceholders = true,
        // 预刷新的距离，距离最后一个 item 多远时加载数据
        // 默认为 pageSize
        prefetchDistance = PAGE_SIZE,
        // 初始化加载数量，默认为 pageSize * 3
        initialLoadSize = PAGE_SIZE
    )

    @OptIn(ExperimentalPagingApi::class)
    fun getPagingData2(context: Context): Flow<PagingData<Repo>> {
        return Pager(
            config = pagingConfig,
            remoteMediator = RepoMediator(gitHubService, db, context)
        ) {
            db.repoDao().get()
        }.flow.map { pagingData ->
            pagingData.map {
                Repo(
                    id = it.id,
                    name = it.name,
                    description = it.description,
                    starCount = it.starCount
                )
            }
        }
    }
}